package main

import (
	"bufio"
	"bytes"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"
)

func main() {
	for {
		// 读入一行，`\n`结束;
		inputReader := bufio.NewReader(os.Stdin)
		input, err := inputReader.ReadString('\n')
		if err != nil {
			log.Printf("[args error]:%s", err.Error())
			continue
		}

		// 依照空格分成多个参数;
		shellArgs := strings.Fields(input)
		if len(shellArgs) == 0 {
			continue
		}

		// 退出tinyShell
		if len(shellArgs) == 1 && shellArgs[0] == "quit" || shellArgs[0] == "q" {
			break
		}

		// handle pipe;
		// 先看只有一个管道的情况
		var havePile bool
		var firstArgs []string
		var secondArgs []string

		//找到有多少个管道`|`
		// var seprateArgs []([]string)
		// var count int
		// var cur int
		// for index, args := range shellArgs {
		// 	if
		// }
		fmt.Println(seprateArgs)
		fmt.Println(count)
		// ///////////////////

		// 初始化输出buffer
		var outBuffer []*bufio.Reader = make([]*bufio.Reader, count)

		for i := 0; i < count; i++ {
			cmd := exec.Command(seprateArgs[i])
		}

		for index, arg := range shellArgs {
			if arg == "|" {
				havePile = true
				firstArgs = shellArgs[0:index]
				secondArgs = shellArgs[index+1:]
			}
		}

		if havePile {

			cmd1 := exec.Command(firstArgs[0], firstArgs[1:]...)
			cmd2 := exec.Command(secondArgs[0], secondArgs[1:]...)
			stdout, err := cmd1.StdoutPipe()
			if err != nil {
				fmt.Println(err.Error())
				return
			}
			err = cmd1.Start()
			if err != nil {
				log.Println(err.Error())
				return
			}
			outputBuf1 := bufio.NewReader(stdout)

			stdin2, err := cmd2.StdinPipe()
			if err != nil {
				log.Println(err.Error())
				return
			}
			outputBuf1.WriteTo(stdin2)
			var outputBuf2 bytes.Buffer
			cmd2.Stdout = &outputBuf2
			err = cmd2.Start()
			if err != nil {
				log.Println(err.Error())
				return
			}
			err = stdin2.Close()
			if err != nil {
				log.Println(err.Error())
				return
			}
			err = cmd2.Wait()
			if err != nil {
				log.Println(err.Error())
				return
			}
			fmt.Println("result:", cmd2.Stdout)

		}
	}
}
